// Package cmd /*
package cmd

import (
	"github.com/chmodke/gitmm/git"
	"github.com/chmodke/gitmm/log"
	"github.com/chmodke/gitmm/util"
	"github.com/spf13/cobra"
	"os"
)

// remoteAddCmd represents the remote command
var remoteAddCmd = &cobra.Command{
	Use:     "add [flags] remote_name",
	Short:   "批量添加仓库远程信息",
	Long:    `执行命令遍历work_dir目录下中的git仓库，并添加仓库远程信息。`,
	Example: "gitmm remote add upstream\n对当前工作目录下所有仓库添加upstream远程信息",
	Args:    cobra.MinimumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		remote := args[0]
		match, _ := cmd.Flags().GetString("match")
		invert, _ := cmd.Flags().GetString("invert-match")

		url, ok := Config.GetRemote(remote)
		if ok != nil {
			log.Consolef("未配置%s远端地址\n", remote)
			os.Exit(1)
		}

		pwd, err := os.Getwd()
		if err != nil {
			log.Consoleln("获取工作路径失败")
			return err
		}
		result := make(map[string]string)
		for _, repo := range Config.Repos {
			if !util.Match(repo.Name, match, invert) {
				result[repo.Name] = SKIP
				continue
			}
			log.Consoleln(repo.Name)
			ok := git.RemoteAdd(pwd, repo, url)
			log.Consoleln("")
			if ok {
				result[repo.Name] = OK
			} else {
				result[repo.Name] = FAIL
			}
		}
		util.ExecStatistic("remote add", result)
		return nil
	},
}

func init() {
	remoteCmd.AddCommand(remoteAddCmd)

	remoteAddCmd.Flags().StringP("match", "m", "", "可选，仓库过滤条件，golang正则表达式")
	remoteAddCmd.Flags().StringP("invert-match", "i", "", "可选，仓库反向过滤条件，golang正则表达式")
}
